<template>
  <div>
    <div class="business-query">
      <el-radio-group v-model="businessRadio" @change="businessRadioChange">
        <el-radio-button label="按商家等级设置" value="1" />
        <el-radio-button label="按商家单独设置" value="2" />
        <el-radio-button label="单独设置营销返佣" value="3" />
      </el-radio-group>
      <el-button v-if="businessRadio == 1" type="primary" @click="openBusinessGrade">添加商家等级</el-button>
      <el-button v-if="businessRadio == 2" type="primary" @click="openBusinessDrawer('')">添加单独设置商家返点</el-button>
      <el-button v-if="businessRadio == 3" type="primary" @click="openMarketing('')">单独设置营销返佣</el-button>
    </div>

    <!-- 商家等级设置列表 -->
    <div v-if="businessRadio == 1">
      <el-table v-loading="tableLoading" :data="businessTable" highlight-current-row style="width: 100%; margin-top: 20px">
        <el-table-column label="序号" type="index" width="50" />
        <el-table-column property="businessLevelName" label="商家等级" width="140" />
        <el-table-column property="levelTitle" label="等级描述" width="180" />
        <el-table-column property="businessCount" label="商家数量" />
        <el-table-column property="unsetPurchaseCommissionCount" label="集采返佣" width="180">
          <template #default="scope">
            {{
              scope.row.unsetPurchaseCommissionCount == 0 ? "已设置" : `共${scope.row.unsetPurchaseCommissionCount}个工厂未设置`
            }}
          </template>
        </el-table-column>
        <el-table-column property="" label="营销返佣" width="100"
          ><template #default="scope">
            {{ scope.row.isSetSales ? "已设置" : "未设置" }}
          </template>
        </el-table-column>
        <el-table-column property="createBy" label="创建人" width="120" />
        <el-table-column property="createTime" label="创建日期" width="120" />
        <el-table-column property="updateBy" label="更新人" width="120" />
        <el-table-column property="updateTime" label="更新日期" width="120" />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button link type="primary" @click="toPath(scope.row)"> 管理集采返佣 </el-button>
            <el-button link type="primary" @click="openMarketing(scope.row)"> 设置营销返佣 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 商家单独设置列表 -->
    <div v-if="businessRadio == 2">
      <el-form class="alone-business" :model="queryBusiness" ref="queryBusinessRef" :inline="true" label-width="68px">
        <el-form-item label="商家名称" prop="businessName">
          <el-input v-model="queryBusiness.businessName" placeholder="请输入" style="width: 240px" autosize clearable />
        </el-form-item>
        <el-form-item label="工厂名称" prop="factoryName">
          <el-input v-model="queryBusiness.factoryName" placeholder="请输入" style="width: 240px" autosize clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="searchData">查询</el-button>
          <el-button icon="Refresh" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 商家单独设置表格 -->
      <el-radio-group v-model="queryBusiness.aloneSet" @change="aloneSetChange">
        <el-radio value="0" size="large">全部（{{ aloneCount.allCount }}）</el-radio>
        <el-radio value="1" size="large">续约调整（{{ aloneCount.renewSetCount }}）</el-radio>
      </el-radio-group>
      <template v-if="queryBusiness.aloneSet == 0">
        <el-table v-loading="tableLoading" :data="businessTable" highlight-current-row style="width: 100%; margin-top: 20px">
          <el-table-column label="序号" type="index" width="50" />
          <el-table-column property="businessName" label="商家名称" width="250" />
          <el-table-column property="factoryName" label="工厂名称" width="250" />
          <el-table-column property="settingBy" label="设置人" />
          <el-table-column property="settingTime" label="设置日期" />
          <el-table-column property="updateBy" label="更新人" width="120" />
          <el-table-column property="updateTime" label="更新日期" width="120" />
          <el-table-column fixed="right" label="操作" width="160">
            <template #default="scope">
              <el-button link type="primary" @click="openBusinessDrawer(scope.row)"> 编辑 </el-button>
              <el-button link type="primary" @click="cancelBusiness(scope.row)"> 取消设置 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template v-if="queryBusiness.aloneSet == 1">
        <el-table v-loading="tableLoading" :data="businessTable" highlight-current-row style="width: 100%; margin-top: 20px">
          <el-table-column label="序号" type="index" width="50" />
          <el-table-column property="businessName" label="商家名称" width="250" />
          <el-table-column property="factoryName" label="工厂名称" width="250" />
          <el-table-column property="renewStartTime" label="续约开始日期" />
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
              <el-button link type="primary" @click="openBusinessDrawer(scope.row)"> 调整续约返佣 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </div>

    <!-- 单独设置营销返佣列表 -->
    <div v-if="businessRadio == 3">
      <el-form class="alone-business" :model="queryBusiness" ref="queryBusinessRef" :inline="true" label-width="68px">
        <el-form-item label="商家名称" prop="businessName">
          <el-input v-model="queryBusiness.businessName" placeholder="请输入" style="width: 240px" autosize clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="searchData">查询</el-button>
          <el-button icon="Refresh" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="tableLoading" :data="businessTable" highlight-current-row style="width: 100%; margin-top: 20px">
        <el-table-column label="序号" type="index" width="50" />
        <el-table-column property="businessName" label="商家名称" width="250" />
        <el-table-column property="channelTenantName" label="关联渠道" />
        <el-table-column property="channelSalesRatio" label="渠道营销返点" width="120" />
        <el-table-column property="exhibitionHallRatio" label="展厅营销返点" width="120" />
        <el-table-column property="settingBy" label="创建人" width="120" />
        <el-table-column property="settingTime" label="创建日期" width="120" />
        <el-table-column property="updateBy" label="更新人" width="120" />
        <el-table-column property="updateTime" label="更新日期" width="120" />
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <el-button link type="primary" @click="openMarketing(scope.row)"> 编辑 </el-button>
            <el-button link type="primary" @click="cancelBusiness(scope.row)"> 取消单独设置 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination
      :total="listTotal"
      v-model:page="queryBusiness.current"
      v-model:limit="queryBusiness.size"
      @pagination="paginationChange"
    />

    <!-- 添加商家等级弹窗 -->
    <el-dialog v-model="businessGradeDialog" width="474" title="添加商家等级" @close="closeBusinessGrade(businessGradeRef)">
      <el-form ref="businessGradeRef" :model="businessGradeForm" :rules="businessGradeRules" label-width="auto">
        <el-form-item label="等级名称" prop="businessLevelName">
          <el-input v-model="businessGradeForm.businessLevelName" placeholder="请输入" style="width: 100%" autosize clearable />
        </el-form-item>

        <el-form-item label="等级说明">
          <el-input
            v-model="businessGradeForm.levelTitle"
            type="textarea"
            placeholder="请输入"
            :autosize="{ minRows: 2, maxRows: 4 }"
            style="width: 100%"
            autosize
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: center">
          <el-button class="btn" @click="closeBusinessGrade(businessGradeRef)">取消</el-button>
          <el-button class="btn" :loading="gradeBtnLoading" type="primary" @click="sumbitBusinessGrade(businessGradeRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 取消商家设置/取消单独设置营销返佣 弹窗 -->
    <el-dialog
      v-model="cancelBusinessDialog"
      :close-on-click-modal="false"
      width="474"
      title=""
      @close="closeCancelBusinessDialog"
    >
      <div style="text-align: center">
        <el-icon color="#F56C6C" size="70"><Warning /></el-icon>
      </div>
      <div style="text-align: center; margin-top: 40px; margin-bottom: 30px">{{ cancelBusinessTitle }}</div>
      <template #footer>
        <div style="text-align: center">
          <el-button class="btn" @click="closeCancelBusinessDialog">取消</el-button>
          <el-button class="btn" :loading="canceBtnLoading" type="primary" @click="cancelBusinessSure"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 商家抽屉 -->
    <business-drawer
      v-if="isBusinessDrawer"
      :renewalDrawer="isBusinessDrawer"
      :title="queryBusiness.aloneSet == 0 ? '单独设置商家返点' : '更新商家返佣'"
      :isEdit="isEdit"
      :businessFormData="businessFormData"
      @businessChangeDrawer="businessChange"
      @factoryChangeDrawer="factoryChange"
      @closeDeawerEmits="renewalDrawerChang"
      @businessInfoSubmit="businessInfoSubmit"
      @openreRenewalDrawer="openreRenewalDrawer"
    ></business-drawer>
    <!-- 详情里点击查看续约---抽屉 -->
    <business-drawer
      v-if="isUpBusinessDrawer"
      :renewalDrawer="isUpBusinessDrawer"
      :title="'更新商家返佣'"
      :isEdit="isUpBusinessEdit"
      :businessFormData="businessRenewalFormData"
      @closeDeawerEmits="isUpBusinessDrawerChang"
      @businessInfoSubmit="isUpBusinessInfoSubmit"
    ></business-drawer>
    <!-- 商家等级设置营销返佣/单独设置营销返佣 设置营销返佣--抽屉 -->
    <el-drawer
      title="设置营销返佣"
      v-model="marketingDrawer"
      @close="closeMarketing(marketingFormRef)"
      size="500px"
      append-to-body
      class="rebate-rules-drawer"
    >
      <div class="spase">
        <el-scrollbar max-height="calc(100vh - 90px)">
          <el-form
            style="width: 100%"
            ref="marketingFormRef"
            :model="marketingForm"
            :rules="marketingRules"
            label-position="top"
            label-width="80px"
          >
            <template v-if="businessRadio == 3">
              <el-form-item label="商家名称" prop="name">
                <el-select-v2
                  v-if="isMarketingEdit"
                  v-model="marketingForm.businessId"
                  :options="businessMarketingOption"
                  :props="businessMarketingProps"
                  filterable
                  placeholder="请选择"
                />
                <div v-else>{{ marketingForm.businessName }}</div>
              </el-form-item>
              <el-form-item label="渠道营销返佣比例" prop="channelSalesRatio">
                <el-input-number
                  class="hidden-controls"
                  v-model="marketingForm.channelSalesRatio"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  :max="100"
                />%
              </el-form-item>
            </template>
            <template v-if="businessRadio == 1">
              <el-form-item label="商家等级">
                <div>{{ marketingForm.businessLevelName }}</div>
              </el-form-item>
              <el-form-item label="渠道营销返佣比例" prop="channelMarketingRatio">
                <el-input-number
                  class="hidden-controls"
                  v-model="marketingForm.channelMarketingRatio"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  :max="100"
                />%
              </el-form-item>
            </template>
            <el-form-item label="展厅营销返佣比例" prop="exhibitionHallRatio">
              <el-input-number
                class="hidden-controls"
                v-model="marketingForm.exhibitionHallRatio"
                :precision="2"
                :step="0.1"
                :min="0"
                :max="100"
              />%
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>

      <template #footer>
        <div style="text-align: center">
          <el-button class="btn" @click="closeMarketing(marketingFormRef)">取 消</el-button>
          <el-button class="btn" :loading="marketingBtn" type="primary" @click="submitMarketing(marketingFormRef)">
            确 定
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script setup>
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import businessDrawer from "./components/businessDrawer.vue";
import {
  pageList,
  listFactory,
  listBusiness,
  getFactoryRatioByFactoryId,
  insertBusinessRatio,
  addLevel,
  settingPage,
  cancelBusinessRatio,
  renewPageList,
  getDetail,
  updateBusinessRatio,
  getRenewDetail,
  insertRenewRatio,
  unSetRenewDetail,
  factoryBusinessCount,
  salesDetail,
  addOrUpdateSales,
  salesPageList,
  listUnsetSalesBusiness,
  salesAdd,
  onlySalesDetail,
  salesDelete
} from "@/api/system/rebateRules/business";
import { onMounted, reactive } from "vue";
const route = useRoute();
const router = useRouter();
// 商家类型单选
const businessRadio = ref("1");
// 商家等级弹窗
const businessGradeDialog = ref(false);
const businessGradeRef = ref();
const businessGradeForm = ref({
  businessLevelName: "",
  levelTitle: ""
});
// 商家等级表单校验
const businessGradeRules = {
  businessLevelName: [{ required: true, message: "请输入等级名称", trigger: "blur" }]
};
// 搜索条件
const queryBusiness = ref({
  businessName: "",
  factoryName: "",
  aloneSet: "0",
  current: 1,
  size: 10
});
const queryBusinessRef = ref();
// 商家表格
const businessTable = ref([]);
// 商家表格总数
const listTotal = ref(0);
// 商家抽屉是否弹出
const isBusinessDrawer = ref(false);

// 商家类型单选变化
const businessRadioChange = value => {
  // 搜索条件
  queryBusiness.value = {
    businessName: "",
    factoryName: "",
    aloneSet: "0",
    current: 1,
    size: 10
  };

  businessTable.value = [];
  tabsPageJudge();
  if (businessRadio.value == 2) {
    getFactoryBusinessCount();
  }
};

const aloneCount = ref({
  allCount: 0,
  renewSetCount: 0
});
// 商家单独设置统计：全部，续约设置
const getFactoryBusinessCount = () => {
  factoryBusinessCount().then(res => {
    aloneCount.value = res.data;
  });
};

const gradeBtnLoading = ref(false);
// 打开商家等级弹窗
const openBusinessGrade = () => {
  businessGradeDialog.value = true;
};
// 关闭商家等级弹窗
const closeBusinessGrade = formRef => {
  if (!formRef) return;
  businessGradeDialog.value = false;
  gradeBtnLoading.value = false;
  formRef.resetFields();
  businessGradeForm.value = {
    businessLevelName: "",
    levelTitle: ""
  };
};
// 提交商家等级
const sumbitBusinessGrade = formRef => {
  if (!formRef) return;
  formRef.validate((valid, fields) => {
    if (valid) {
      gradeBtnLoading.value = true;
      addLevel(businessGradeForm.value)
        .then(res => {
          closeBusinessGrade(businessGradeRef.value);
          tabsPageJudge();
        })
        .catch(err => {
          gradeBtnLoading.value = false;
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 跳转商家等级列表页面
const toPath = row => {
  router.push({
    path: "rebateRules/businessGrade",
    query: {
      businessLevelId: row.businessLevelId,
      businessLevelName: row.businessLevelName
    }
  });
};

// 查询
const searchData = () => {
  tabsPageJudge();
};

// 搜索重置
const reset = () => {
  queryBusiness.value = {
    businessName: "",
    factoryName: "",
    aloneSet: queryBusiness.value?.aloneSet,
    current: 1,
    size: 10
  };
  tabsPageJudge();
};

// 单独设置商家列表-页码变化
const paginationChange = () => {
  tabsPageJudge();
};

//  单独设置tab变化
const aloneSetChange = value => {
  tabsPageJudge();
};

const isEdit = ref(true);

const businessFormData = ref({});
// 打开商家单独设置商家抽屉
const openBusinessDrawer = row => {
  isBusinessDrawer.value = true;
  businessFormData.value = {};
  isEdit.value = true;
  getDrawerFactory();
  getDrawerBusiness();

  if (row) {
    if (queryBusiness.value.aloneSet == 0) {
      isEdit.value = false;
      businessFormData.value.darwerType = "编辑";
      getEditDetail(row);
    } else {
      getBusinessRenewDetail(row);
    }
  }
};

// 获取单独设置商家返点详情
const getEditDetail = row => {
  businessFormData.value.isLoading = true;
  getDetail(row).then(res => {
    res.data.ratioVos?.forEach(item => {
      item.amount = Number(item.amount);
      item.commissionRatio = Number(item.businessRatio);
      item.factoryRatio = Number(item.factoryRatio);
    });
    res.data.businessFormTable = res.data.ratioVos;
    businessFormData.value = { ...businessFormData.value, ...res.data };
    businessFormData.value.isLoading = false;
  });
};

// 查询未设置调整续约详情
const getBusinessRenewDetail = row => {
  businessFormData.value.isLoading = true;
  unSetRenewDetail(row).then(res => {
    res.data.ratioVos?.forEach(item => {
      item.amount = Number(item.amount);
      item.commissionRatio = Number(item.businessRatio);
      item.factoryRatio = Number(item.factoryCommissionRatio);
    });
    res.data.renewRatioVos?.forEach(item => {
      item.amount = Number(item.amount);
      item.commissionRatio = null;
      item.factoryRatio = Number(item.factoryCommissionRatio);
    });
    res.data.hasRenew = true;
    res.data.businessFormTable = res.data.ratioVos;
    res.data.businessAfterFormTable = res.data.renewRatioVos;
    businessFormData.value = { ...businessFormData.value, ...res.data };
    businessFormData.value.isLoading = false;
  });
};

// 获取单独设置弹窗工厂数据
const getDrawerFactory = () => {
  listFactory().then(res => {
    businessFormData.value.factoryOptions = res.data;
  });
};

// 获取单独设置商家数据
const getDrawerBusiness = () => {
  listBusiness().then(res => {
    businessFormData.value.businessOptions = res.data;
  });
};

// 抽屉-商家变换
const businessChange = value => {
  getProportion();
};

// 抽屉-工厂变换
const factoryChange = value => {
  getProportion();
};

// 查询比例
const getProportion = () => {
  businessFormData.value.hasRenew = false;
  if (businessFormData.value.factoryId && businessFormData.value.businessId) {
    businessFormData.value.isLoading = true;
    let query = {
      factoryId: businessFormData.value.factoryId,
      businessId: businessFormData.value.businessId
    };
    getFactoryRatioByFactoryId(query)
      .then(res => {
        res.data.ratioVos?.forEach(item => {
          item.amount = Number(item.amount);
          item.factoryRatio = Number(item.factoryRatio);
        });
        businessFormData.value.businessFormTable = res.data.ratioVos;
        if (res.data.renewRatioVos && res.data.renewRatioVos.length > 0) {
          res.data.renewRatioVos?.forEach(item => {
            item.amount = Number(item.amount);
            item.factoryRatio = Number(item.factoryRatio);
          });
          businessFormData.value.businessAfterFormTable = res.data.renewRatioVos;
          businessFormData.value.hasRenew = true;
        }
        businessFormData.value.factoryCommissionId = res.data.factoryCommissionId;
        businessFormData.value.isLoading = false;
      })
      .catch(err => {
        businessFormData.value.businessFormTable = [];
        businessFormData.value.isLoading = false;
      });
  }
};

// 关闭商家抽屉
const renewalDrawerChang = value => {
  isBusinessDrawer.value = value;
};

// 详情里点击查看续约---抽屉
const isUpBusinessDrawer = ref(false);
const isUpBusinessEdit = ref(true);
const businessRenewalFormData = ref({});
const openreRenewalDrawer = value => {
  isUpBusinessDrawer.value = true;
  businessRenewalFormData.value = {};
  isUpBusinessEdit.value = false;
  businessRenewalFormData.value.isLoading = true;
  getRenewDetail(businessFormData.value).then(res => {
    res.data.ratioVos?.forEach(item => {
      item.amount = Number(item.amount);
      item.commissionRatio = Number(item.businessRatio);
      item.factoryRatio = Number(item.factoryRatio);
    });
    res.data.renewRatioVos?.forEach(item => {
      item.amount = Number(item.amount);
      item.commissionRatio = Number(item.businessRatio);
      item.factoryRatio = Number(item.factoryRatio);
    });
    res.data.hasRenew = true;
    res.data.businessFormTable = res.data.ratioVos;
    res.data.businessAfterFormTable = res.data.renewRatioVos;
    businessRenewalFormData.value = { ...businessRenewalFormData.value, ...res.data };
    businessRenewalFormData.value.isLoading = false;
  });
};

// 跟新商家续约信息
const isUpBusinessInfoSubmit = value => {
  // 单独商家--续约调整判断
  let businessAfterFormTable = businessRenewalFormData.value.businessAfterFormTable;

  let arfterRatioJudge = businessAfterFormTable.every(item => item.commissionRatio > 0);
  if (!arfterRatioJudge) {
    ElMessage.error("请输入对应等级商家返点");
    return;
  }
  // 返点比例，判断下一阶梯返点比例必须>=上一级,
  if (businessAfterFormTable.length > 1) {
    for (let i = 0; i < businessAfterFormTable.length; i++) {
      let ratio = businessAfterFormTable[i].commissionRatio;
      if (i > 0) {
        if (ratio < businessAfterFormTable[i - 1].commissionRatio) {
          ElMessage.error("对应等级商家返点输入错误");
          return;
        }
      }
    }
  }

  businessRenewalFormData.value.renewRatios = businessRenewalFormData.value.businessAfterFormTable;
  businessRenewalFormData.value.buttonLoading = true;

  addBusinessRenew(businessRenewalFormData);
};

const isUpBusinessDrawerChang = value => {
  isUpBusinessDrawer.value = value;
};

const cancelBusinessDialog = ref(false);
const cancelId = ref(0);
const cancelBusinessTitle = ref("");
// 打开取消商家弹窗
const cancelBusiness = row => {
  if (businessRadio.value == 2) {
    cancelBusinessTitle.value = "请确认是否取消该商家单独设置返佣";
    cancelId.value = row.factoryBusinessCommissionId;
  } else if (businessRadio.value == 3) {
    cancelBusinessTitle.value = "请确认是否取消该商家单独设置营销";
    cancelId.value = row.businessId;
  }
  cancelBusinessDialog.value = true;
};
// 关闭取消商家弹窗
const closeCancelBusinessDialog = () => {
  canceBtnLoading.value = false;
  cancelBusinessDialog.value = false;
};
const canceBtnLoading = ref(false);
// 取消商家弹窗-确定
const cancelBusinessSure = () => {
  canceBtnLoading.value = true;
  if (businessRadio.value == 2) {
    cancelBusinessRatio({ factoryBusinessCommissionId: cancelId.value })
      .then(res => {
        closeCancelBusinessDialog();
        ElMessage.success("取消成功");
        tabsPageJudge();
      })
      .catch(err => {
        canceBtnLoading.value = false;
      });
  } else if (businessRadio.value == 3) {
    salesDelete(cancelId.value)
      .then(res => {
        closeCancelBusinessDialog();
        ElMessage.success("取消成功");
        tabsPageJudge();
      })
      .catch(err => {
        canceBtnLoading.value = false;
      });
  }
};
// 商家设置信息
const businessInfoSubmit = value => {
  let businessFormTable = businessFormData.value.businessFormTable;
  let commissionRatioJudge = businessFormTable.every(item => item.commissionRatio > 0);
  if (!commissionRatioJudge) {
    ElMessage.error("请输入对应等级商家返点");
    return;
  }

  // 返点比例多条数据，判断下一阶梯返点比例必须>=上一级,
  if (businessFormTable.length > 1) {
    for (let i = 0; i < businessFormTable.length; i++) {
      let commissionRatio = businessFormTable[i].commissionRatio;
      if (i > 0) {
        if (commissionRatio < businessFormTable[i - 1].commissionRatio) {
          ElMessage.error("对应等级商家返点输入错误");
          return;
        }
      }
    }
  }

  // 单独商家--续约调整判断
  let businessAfterFormTable = businessFormData.value.businessAfterFormTable;
  if (businessAfterFormTable) {
    let arfterRatioJudge = businessAfterFormTable.every(item => item.commissionRatio > 0);
    if (!arfterRatioJudge) {
      ElMessage.error("请输入对应等级商家返点");
      return;
    }
    // 返点比例，判断下一阶梯返点比例必须>=上一级,
    if (businessAfterFormTable.length > 1) {
      for (let i = 0; i < businessAfterFormTable.length; i++) {
        let ratio = businessAfterFormTable[i].commissionRatio;
        if (i > 0) {
          if (ratio < businessAfterFormTable[i - 1].commissionRatio) {
            ElMessage.error("对应等级商家返点输入错误");
            return;
          }
        }
      }
    }
  }

  businessFormData.value.businessName = businessFormData.value.businessOptions.find(item => {
    return item.businessId == businessFormData.value.businessId;
  }).businessName;
  businessFormData.value.factoryName = businessFormData.value.factoryOptions.find(item => {
    return item.factoryId == businessFormData.value.factoryId;
  }).factoryName;
  businessFormData.value.businessRatios = businessFormData.value.businessFormTable;
  businessFormData.value.renewRatios = businessFormData.value.businessAfterFormTable;
  businessFormData.value.buttonLoading = true;

  if (queryBusiness.value.aloneSet == 0) {
    if (businessFormData.value.darwerType == "编辑") {
      // 编辑当前返佣比例提交
      editBusiness();
    } else {
      // 新增提交
      addBusiness();
    }
  } else {
    // 新增续约提交
    addBusinessRenew(businessFormData);
  }
};

// 新增单独商家续约
const addBusinessRenew = data => {
  insertRenewRatio(data.value)
    .then(res => {
      isBusinessDrawer.value = false;
      isUpBusinessDrawer.value = false;
      data.value.buttonLoading = false;
      ElMessage.success("调整成功");
      tabsPageJudge();
    })
    .catch(err => {
      data.value.buttonLoading = false;
    });
};

// 编辑单独商家
const editBusiness = () => {
  updateBusinessRatio(businessFormData.value)
    .then(res => {
      isBusinessDrawer.value = false;
      businessFormData.value.buttonLoading = false;
      ElMessage.success("编辑成功");
      tabsPageJudge();
    })
    .catch(err => {
      businessFormData.value.buttonLoading = false;
    });
};

// 新增单独商家
const addBusiness = () => {
  insertBusinessRatio(businessFormData.value)
    .then(res => {
      isBusinessDrawer.value = false;
      businessFormData.value.buttonLoading = false;
      ElMessage.success("设置成功");
      tabsPageJudge();
    })
    .catch(err => {
      businessFormData.value.buttonLoading = false;
    });
};

const marketingDrawer = ref(false);
const marketingForm = ref({});
const marketingRules = {
  channelMarketingRatio: [{ required: true, message: "请输入渠道营销返点比例", trigger: "blur" }],
  channelSalesRatio: [{ required: true, message: "请输入渠道营销返点比例", trigger: "blur" }],
  exhibitionHallRatio: [{ required: true, message: "请输入展厅营销返点比例", trigger: "blur" }]
};
const marketingFormRef = ref();
const marketingBtn = ref(false);
const isMarketingEdit = ref(true);
// 单独设置营销返佣的商户数据
const businessMarketingOption = ref([]);
const businessMarketingProps = {
  label: "businessName",
  value: "businessId"
};
// 打开营销返佣抽屉
const openMarketing = row => {
  marketingDrawer.value = true;
  isMarketingEdit.value = true;
  if (row) {
    if (businessRadio.value == 1) {
      salesDetail(row.businessLevelId).then(res => {
        res.data.channelMarketingRatio = Number(res.data.channelMarketingRatio);
        res.data.exhibitionHallRatio = Number(res.data.exhibitionHallRatio);
        marketingForm.value = res.data;
      });
    } else {
      isMarketingEdit.value = false;
      onlySalesDetail(row.businessId).then(res => {
        res.data.channelSalesRatio = Number(res.data.channelSalesRatio);
        res.data.exhibitionHallRatio = Number(res.data.exhibitionHallRatio);
        marketingForm.value = res.data;
      });
    }
  } else {
    // 单独设置营销返佣 && 新建
    if (businessRadio.value == 3) {
      listUnsetSalesBusiness().then(res => {
        businessMarketingOption.value = res.data;
      });
    }
  }
};
// 关闭营销抽屉
const closeMarketing = formRef => {
  if (!formRef) return;
  marketingDrawer.value = false;
  marketingForm.value = {};
  marketingBtn.value = false;
  formRef.resetFields();
};
// 提交营销设置
const submitMarketing = formRef => {
  if (!formRef) return;
  formRef.validate((valid, fields) => {
    if (valid) {
      marketingBtn.value = true;
      if (businessRadio.value == 1) {
        addOrUpdateSales(marketingForm.value)
          .then(res => {
            ElMessage.success("操作成功");
            closeMarketing(marketingFormRef.value);
            tabsPageJudge();
          })
          .catch(err => {
            marketingBtn.value = false;
          });
      } else if (businessRadio.value == 3) {
        salesAdd(marketingForm.value)
          .then(res => {
            ElMessage.success("操作成功");
            closeMarketing(marketingFormRef.value);
            tabsPageJudge();
          })
          .catch(err => {
            marketingBtn.value = false;
          });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 根据选中tabs按钮获取页面数据
const tabsPageJudge = () => {
  if (businessRadio.value == 1) {
    getLeveList();
  } else if (businessRadio.value == 2) {
    pageListJudge();
  } else if (businessRadio.value == 3) {
    getSalesPageList();
  }
};

// 单独设置商家列表--判断查询
const pageListJudge = () => {
  if (queryBusiness.value.aloneSet === "0") {
    getTable(queryBusinessRef.value);
  } else {
    getRenewPageList(queryBusinessRef.value);
  }
};

const tableLoading = ref(false);

// 获取续约调整列表
const getRenewPageList = formRef => {
  if (!formRef) return;
  formRef.validate((valid, fields) => {
    if (valid) {
      tableLoading.value = true;
      renewPageList(queryBusiness.value).then(res => {
        res.data.list?.forEach(item => {
          item.renewStartTime = item.renewStartTime?.split(" ")[0];
        });
        businessTable.value = res.data.list;
        listTotal.value = res.data.total;
        aloneCount.value.renewSetCount = res.data.total;
        tableLoading.value = false;
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 获取商家单独设置列表
const getTable = formRef => {
  if (!formRef) return;
  formRef.validate((valid, fields) => {
    if (valid) {
      tableLoading.value = true;
      pageList(queryBusiness.value).then(res => {
        res.data.list?.forEach(item => {
          item.settingTime = item.settingTime?.split(" ")[0];
          item.updateTime = item.updateTime?.split(" ")[0];
        });
        businessTable.value = res.data.list;
        listTotal.value = res.data.total;
        aloneCount.value.allCount = res.data.total;
        tableLoading.value = false;
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 获取商家等级列表
const getLeveList = () => {
  tableLoading.value = true;
  settingPage(queryBusiness.value).then(res => {
    businessTable.value = res.data.list;
    listTotal.value = res.data.total;
    tableLoading.value = false;
  });
};

// 获取商家单独设置营销返佣列表
const getSalesPageList = () => {
  tableLoading.value = true;
  salesPageList(queryBusiness.value).then(res => {
    businessTable.value = res.data.list;
    listTotal.value = res.data.total;
    tableLoading.value = false;
  });
};

onMounted(() => {
  tabsPageJudge();
});
</script>

<style lang="scss" scoped>
.business-query {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.business-item {
  &-box {
    padding: 20px;
    padding-top: 0;
    background: #f5f7fa;
    border-radius: 4px;
    margin-top: 20px;
    &-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 44px;
      border-bottom: 1px solid #e2e8f0;
    }
    &-row {
      margin-top: 20px;
    }
  }
  .row-bg {
    margin-top: 10px;
  }
}
.alone-business {
  margin-top: 20px;
}

.btn {
  width: 120px;
  height: 36px;
  line-height: 36px;
}
</style>
